package com.njlime.cms.service.sys;

import com.njlime.cms.entities.Live;
import com.njlime.cms.repository.sys.LiveDao;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.sys.service.UnitService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by Dean on 2017/8/11.
 */
@Service
@Transactional(readOnly = true)
public class LiveService {

    @Resource
    LiveDao liveDao;
    @Resource
    private UnitService unitService;

    /**
     * 详情
     *
     * @param id
     * @return
     */
    public Live findOne(int id) {
        return liveDao.findOne(id);
    }

    /**
     * 保存
     *
     * @param live
     * @return
     */
    @Transactional(readOnly = false)
    public int save(Live live) {
        live.setRoot_unit_id(unitService.getRootUnit(live.getUnit_id()));
        live.setComment_num(0);
        live.setReading(0);
        live.setIs_del(GlobalValue.NO);
        live.setCreate_time(new Date());
        live.setIs_comment(GlobalValue.NO);
        live.setPublish_status(GlobalValue.PublishStatus.UNPUBLISHED);
        live = liveDao.save(live);
        return live.getId();
    }

    /**
     * 编辑
     *
     * @param live
     * @return
     */
    @Transactional(readOnly = false)
    public int editLive(Live live) {
        return liveDao.editLive(live);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public int del(int id) {
        return liveDao.del(id);
    }

    /**
     * 评论开关
     *
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public int toggleComment(int id) {
        return liveDao.toggleComment(id);
    }

    /**
     * 上下线
     *
     * @param live
     * @return
     */
    @Transactional(readOnly = false)
    public int togglePublish(Live live) {
        if(live.getPublish_status() != GlobalValue.PublishStatus.PUBLISHED){
            live.setPublish_status(GlobalValue.PublishStatus.PUBLISHED);
        }else{
            live.setPublish_status(GlobalValue.PublishStatus.CANCELED);
        }
        return liveDao.editLive(live);
    }

    /**
     * 分页列表
     *
     * @param pageBean
     * @param tLive
     * @return
     */
    public PageBean list(PageBean pageBean, Live tLive) {
        return liveDao.list(pageBean, tLive);
    }

    /**
     * 更新评论数量
     *
     * @param id
     */
    @Transactional(readOnly = false)
    public void updateCommentNum(Integer id, Integer num) {
        liveDao.updateCommentNum(id, num);
    }
}
